package com.example.safeassistan.home.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.model.DepartModel;
import com.example.safeassistan.home.activity.ActivityCheckLog;
import com.example.safeassistan.home.activity.CheckLogSecond;
import com.example.safeassistan.home.activity.HiddenDangerinvestigation;
import com.example.safeassistan.home.adapter.CheckRecordFragmentAdapter;
import com.example.safeassistan.home.adapter.HomeCheckRecordFragmentAdapter;
import com.example.safeassistan.home.model.HomeCheckRecordModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.adapter.DepartSelectedListAdapter;
import com.example.safeassistan.risk.adapter.RiskCheckTableSelectedListAdapter;
import com.example.safeassistan.risk.model.ChecktableListModel;
import com.example.safeassistan.risk.model.DepartListModel;
import com.example.safeassistan.risk.model.RiskDetailCheckLogModel;
import com.example.safeassistan.utile.EventBusBean;
import com.example.safeassistan.utile.JsonUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class CheckRecordFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private SmartRefreshLayout refresh;
    private HomeCheckRecordFragmentAdapter adapter;
    private List<HomeCheckRecordModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcView;
    private TextView line,tvCheckTable,tvCheckResult,tvDegree,tvDepartName;
    private LinearLayout llType4,llType3,llType2,llType1;
    private int currentPage=1;
    private ChecktableListModel checktableListModel;
    private DepartModel departListModel=null;

    private int count=0;
    private String checkTableId="";//检查表id
    private String checkType="0";//检查类型 0 我的 1部门
    private String checkedTime="";//检查时间
    private String departId="";//部门id
    private String riskLevel="";//	风险点等级 1、重大 2、较大 3、一般 4、较低
    private String tableResult="";//检查结果


    public static CheckRecordFragment newInstance(String  type) {
        Bundle arguments = new Bundle();
        arguments.putString("type",type);
        CheckRecordFragment fl = new CheckRecordFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.checkrecordfragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    PopupWindow popupWindow;

    public void initView(){
        Bundle bundle = getArguments();
        checkType = bundle.getString("type");
        rcView=view.findViewById(R.id.rcView);
        refresh=view.findViewById(R.id.refresh);
        llType1=view.findViewById(R.id.llType1);
        llType2=view.findViewById(R.id.llType2);
        llType3=view.findViewById(R.id.llType3);
        llType4=view.findViewById(R.id.llType4);
        tvDepartName=view.findViewById(R.id.tvDepartName);
        tvCheckTable=view.findViewById(R.id.tvCheckTable);
        tvCheckResult=view.findViewById(R.id.tvCheckResult);
        tvDegree=view.findViewById(R.id.tvDegree);
        line=view.findViewById(R.id.line);
        llType1.setOnClickListener(this);
        llType2.setOnClickListener(this);
        llType3.setOnClickListener(this);
        llType4.setOnClickListener(this);

        if(checkType.equals("0")){
            llType4.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
        }else {
            llType4.setVisibility(View.VISIBLE);
        }

        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        checkedTime=sp.format(System.currentTimeMillis());
        setView();
        getTabletListData();
        getDepartListData();
        getData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upLoadSuccess(EventBusBean eventBus){
        if (eventBus.getCode()==100){
            checkedTime=eventBus.getMsg();
            getData();
        }
}

    public void getDepartListData(){
        new HttpRequest(context).doPost(UrlConstants.getDepartById, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), DepartModel.class);
                        if (obj instanceof DepartModel) {
                            departListModel=(DepartModel) obj;
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    public void getTabletListData(){
        new HttpRequest(context).doGet(UrlConstants.getAllTableList, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), ChecktableListModel.class);
                        if (obj instanceof ChecktableListModel) {
                            checktableListModel=(ChecktableListModel) obj;
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            EventBus.getDefault().register(this);
        }else {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llType1:
                View inflate = LayoutInflater.from(context).inflate(R.layout.layout_popuwindow_department,null);
                TextView tvAlls=inflate.findViewById(R.id.tvAll);
                tvAlls.setText("检查表筛选");
                tvAlls.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkTableId="";
                        popupWindow.dismiss();
                        tvCheckTable.setText("检查表筛选");
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                RecyclerView rcView=inflate.findViewById(R.id.rcView);
                RiskCheckTableSelectedListAdapter adapter=new RiskCheckTableSelectedListAdapter(checktableListModel.getResult());
                rcView.setAdapter(adapter);
                rcView.setLayoutManager(new LinearLayoutManager(context));
                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        checkTableId=checktableListModel.getResult().get(position).getId();
                        popupWindow.dismiss();
                        tvCheckTable.setText(checktableListModel.getResult().get(position).getTableName());
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(tvCheckTable,0,-100);
                break;
            case R.id.llType2:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_risk_check_result,null);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="";
                        popupWindow.dismiss();
                        tvCheckResult.setText("检查结果");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                TextView tvOk=inflate1.findViewById(R.id.tvBig);
                tvOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="1";
                        popupWindow.dismiss();
                        tvCheckResult.setText("已通过");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvNo=inflate1.findViewById(R.id.tvBigger);
                tvNo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="2";
                        popupWindow.dismiss();
                        tvCheckResult.setText("未通过");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvHidden=inflate1.findViewById(R.id.tvCommon);
                tvHidden.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="3";
                        popupWindow.dismiss();
                        tvCheckResult.setText("存在隐患");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();

                    }
                });
                TextView tvNoRela=inflate1.findViewById(R.id.tvLow);
                tvNoRela.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="0";
                        popupWindow.dismiss();
                        tvCheckResult.setText("未涉及");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(tvCheckResult,0,-100);
                break;
            case R.id.llType3:
                View inflate2 = LayoutInflater.from(context).inflate(R.layout.popu_risk_level,null);
                TextView tvAllDegree=inflate2.findViewById(R.id.tvAll);
                tvAllDegree.setWidth(llType3.getWidth());
                tvAllDegree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel="";
                        popupWindow.dismiss();
                        tvDegree.setText("风险等级");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                TextView tvBig=inflate2.findViewById(R.id.tvBig);
                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel="1";
                        popupWindow.dismiss();
                        tvDegree.setText("重大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvBigger=inflate2.findViewById(R.id.tvBigger);
                tvBigger.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel="2";
                        popupWindow.dismiss();
                        tvDegree.setText("较大风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvCommon=inflate2.findViewById(R.id.tvCommon);
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel="3";
                        popupWindow.dismiss();
                        tvDegree.setText("一般风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvLow=inflate2.findViewById(R.id.tvLow);
                tvLow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        riskLevel="4";
                        popupWindow.dismiss();
                        tvDegree.setText("较低风险");
                        tvDegree.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType3,0,-100);
                break;
            case R.id.llType4:
                //请求部门列表数据
                View inflate3 = LayoutInflater.from(context).inflate(R.layout.layout_popuwindow_department,null);
                TextView tvAllDepart=inflate3.findViewById(R.id.tvAll);
                tvAllDepart.setWidth(llType4.getWidth());
                tvAllDepart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        departId="";
                        popupWindow.dismiss();
                        getData();
                        tvDepartName.setText("部门选择");
                        tvDepartName.setTextColor(context.getResources().getColor(R.color.gray3));
                    }
                });
                RecyclerView rcViews=inflate3.findViewById(R.id.rcView);
                DepartSelectedListAdapter adapters=new DepartSelectedListAdapter(departListModel.getResult());
                rcViews.setAdapter(adapters);
                rcViews.setLayoutManager(new LinearLayoutManager(context));
                adapters.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        departId=departListModel.getResult().get(position).getId();
                        popupWindow.dismiss();
                        tvDepartName.setText(departListModel.getResult().get(position).getName());
                        tvDepartName.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate3, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType4,0,-100);
                break;
        }
    }

    public void reSetStatus(){
        llType1.setBackgroundColor(getResources().getColor(R.color.white));
        llType2.setBackgroundColor(getResources().getColor(R.color.white));
        llType3.setBackgroundColor(getResources().getColor(R.color.white));
        llType4.setBackgroundColor(getResources().getColor(R.color.white));
    }


    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("userId", UserData.create(context).get(UserData.UID));
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("checkedTime",checkedTime);//yyyy-MM-ss
            map.put("checkType",String.valueOf(checkType));

            if (checkTableId!=null&&!checkTableId.equals("")){
                map.put("checkTableId",checkTableId);//检查表id
            }
            if (!riskLevel.equals("")){
                map.put("riskLevel",riskLevel);
            }
            if (tableResult!=null&&!tableResult.equals("")){
                map.put("tableResult",tableResult);
            }
            if (departId!=null&&!departId.equals("")){
                map.put("departId",departId);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.queryCheckedRecordHomePage, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), HomeCheckRecordModel.class);
                        if (obj instanceof HomeCheckRecordModel) {
                            HomeCheckRecordModel model=(HomeCheckRecordModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    data=model.getResult().getRecords();
                                    adapter=new HomeCheckRecordFragmentAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            CheckLogSecond.actionStart(context,data.get(position).getId(),
                                                    data.get(position).getCheckTableId(),data.get(position).getDefRecordId(),data.get(position).getRiskPointId());
                                        }
                                    });
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }
}